<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

	<head>
		<meta charset="utf-8">
		<title>OrderAdmin</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<link rel="stylesheet" href="./css/mui.min.css">
		<style>
			html,
			body {
				background-color: #efeff4;
			}
			
			.mui-bar~.mui-content .mui-fullscreen {
				top: 44px;
				height: auto;
			}
			
			.mui-pull-top-tips {
				position: absolute;
				top: -20px;
				left: 50%;
				margin-left: -25px;
				width: 40px;
				height: 40px;
				border-radius: 100%;
				z-index: 1;
			}
			
			.mui-bar~.mui-pull-top-tips {
				top: 24px;
			}
			
			.mui-pull-top-wrapper {
				width: 42px;
				height: 42px;
				display: block;
				text-align: center;
				background-color: #efeff4;
				border: 1px solid #ddd;
				border-radius: 25px;
				background-clip: padding-box;
				box-shadow: 0 4px 10px #bbb;
				overflow: hidden;
			}
			
			.mui-pull-top-tips.mui-transitioning {
				-webkit-transition-duration: 200ms;
				transition-duration: 200ms;
			}
			
			.mui-pull-top-tips .mui-pull-loading {
				/*-webkit-backface-visibility: hidden;
				-webkit-transition-duration: 400ms;
				transition-duration: 400ms;*/
				margin: 0;
			}
			
			.mui-pull-top-wrapper .mui-icon,
			.mui-pull-top-wrapper .mui-spinner {
				margin-top: 7px;
			}
			
			.mui-pull-top-wrapper .mui-icon.mui-reverse {
				/*-webkit-transform: rotate(180deg) translateZ(0);*/
			}
			
			.mui-pull-bottom-tips {
				text-align: center;
				background-color: #efeff4;
				font-size: 15px;
				line-height: 40px;
				color: #777;
			}
			
			.mui-pull-top-canvas {
				overflow: hidden;
				background-color: #fafafa;
				border-radius: 40px;
				box-shadow: 0 4px 10px #bbb;
				width: 40px;
				height: 40px;
				margin: 0 auto;
			}
			
			.mui-pull-top-canvas canvas {
				width: 40px;
			}
			
			.mui-slider-indicator.mui-segmented-control {
				background-color: #efeff4;
			}
			
			.mui-segmented-control.mui-scroll-wrapper .mui-control-item {
				display: table-cell;
				padding: 0 20px;
				border: 0;
				width: 1%;
			}
			
			.mui-slider .mui-segmented-control.mui-segmented-control-inverted .mui-control-item.mui-active {
				border-bottom: 2px solid #007aff;
				line-height: 20px;
			}
			
			.space5 {
				margin-left: 5px;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a id="menu" class="mui-pull-right" href="javascript:location.reload()" style="line-height:45px;" data-loading-icon="">刷新</a>
			<h1 class="mui-title">订单处理中心</h1>
		</header>
		<div class="mui-content">
			<input type="file" name="image" accept="image/*" onchange='handleInputChange()'>
		</div>

		<script>
			function formatTime(time) {
				var date = new Date(parseInt(time));
				var year = date.getFullYear()
				var month = date.getMonth() + 1
				var day = date.getDate()

				var hour = date.getHours()
				var minute = date.getMinutes()
				var second = date.getSeconds()

				return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
			}

			function formatNumber(n) {
				n = n.toString()
				return n[1] ? n : '0' + n
			}

			var svrUrl = 'https://gzmsbweb.gcn99.com/diancan/';

			// 全局对象，不同function使用传递数据
			const imgFile = {};

			function handleInputChange() {
				// 获取当前选中的文件
				debugger
				const file = this.files[0];
				const imgMasSize = 1024 * 1024 * 10; // 10MB

				// 检查文件类型
				if(['jpeg', 'png', 'gif', 'jpg'].indexOf(file.type.split("/")[1]) < 0) {
					// 自定义报错方式
					// Toast.error("文件类型仅支持 jpeg/png/gif！", 2000, undefined, false);
					return;
				}

				// 文件大小限制
				if(file.size > imgMasSize) {
					// 文件大小自定义限制
					// Toast.error("文件大小不能超过10MB！", 2000, undefined, false);
					return;
				}

				// 判断是否是ios
				if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
					// iOS
					transformFileToFormData(file);
					return;
				}

				// 图片压缩之旅
				transformFileToDataUrl(file);
			}
			// 将File append进 FormData
			function transformFileToFormData(file) {
				const formData = new FormData();
				// 自定义formData中的内容
				// type
				formData.append('type', file.type);
				// size
				formData.append('size', file.size || "image/jpeg");
				// name
				formData.append('name', file.name);
				// lastModifiedDate
				formData.append('lastModifiedDate', file.lastModifiedDate);
				// append 文件
				formData.append('file', file);
				// 上传图片
				uploadImg(formData);
			}
			// 将file转成dataUrl
			function transformFileToDataUrl(file) {
				const imgCompassMaxSize = 200 * 1024; // 超过 200k 就压缩

				// 存储文件相关信息
				imgFile.type = file.type || 'image/jpeg'; // 部分安卓出现获取不到type的情况
				imgFile.size = file.size;
				imgFile.name = file.name;
				imgFile.lastModifiedDate = file.lastModifiedDate;

				// 封装好的函数
				const reader = new FileReader();

				// file转dataUrl是个异步函数，要将代码写在回调里
				reader.onload = function(e) {
					const result = e.target.result;

					if(result.length < imgCompassMaxSize) {
						compress(result, processData, false); // 图片不压缩
					} else {
						compress(result, processData); // 图片压缩
					}
				};

				reader.readAsDataURL(file);
			}
			// 使用canvas绘制图片并压缩
			function compress(dataURL, callback, shouldCompress = true) {
				const img = new window.Image();

				img.src = dataURL;

				img.onload = function() {
					const canvas = document.createElement('canvas');
					const ctx = canvas.getContext('2d');

					canvas.width = img.width;
					canvas.height = img.height;

					ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

					let compressedDataUrl;

					if(shouldCompress) {
						compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2);
					} else {
						compressedDataUrl = canvas.toDataURL(imgFile.type, 1);
					}

					callback(compressedDataUrl);
				}
			}

			function processData(dataURL) {
				// 这里使用二进制方式处理dataUrl
				const binaryString = window.atob(dataUrl.split(',')[1]);
				const arrayBuffer = new ArrayBuffer(binaryString.length);
				const intArray = new Uint8Array(arrayBuffer);
				const imgFile = this.imgFile;

				for(let i = 0, j = binaryString.length; i < j; i++) {
					intArray[i] = binaryString.charCodeAt(i);
				}

				const data = [intArray];

				let blob;

				try {
					blob = new Blob(data, {
						type: imgFile.type
					});
				} catch(error) {
					window.BlobBuilder = window.BlobBuilder ||
						window.WebKitBlobBuilder ||
						window.MozBlobBuilder ||
						window.MSBlobBuilder;
					if(error.name === 'TypeError' && window.BlobBuilder) {
						const builder = new BlobBuilder();
						builder.append(arrayBuffer);
						blob = builder.getBlob(imgFile.type);
					} else {
						// Toast.error("版本过低，不支持上传图片", 2000, undefined, false);
						throw new Error('版本过低，不支持上传图片');
					}
				}

				// blob 转file
				const fileOfBlob = new File([blob], imgFile.name);
				const formData = new FormData();

				// type
				formData.append('type', imgFile.type);
				// size
				formData.append('size', fileOfBlob.size);
				// name
				formData.append('name', imgFile.name);
				// lastModifiedDate
				formData.append('lastModifiedDate', imgFile.lastModifiedDate);
				// append 文件
				formData.append('file', fileOfBlob);

				uploadImg(formData);
			}

			// 上传图片
			function uploadImg(formData) {
				const xhr = new XMLHttpRequest();

				// 进度监听
				xhr.upload.addEventListener('progress', (e) => {
					console.log(e.loaded / e.total)
				}, false);
				// 加载监听
				// xhr.addEventListener('load', ()=>{console.log("加载中");}, false);
				// 错误监听
				xhr.addEventListener('error', () => {
					Toast.error("上传失败！", 2000, undefined, false);
				}, false);
				xhr.onreadystatechange = function() {
					if(xhr.readyState === 4) {
						const result = JSON.parse(xhr.responseText);
						if(xhr.status === 200) {
							// 上传成功

						} else {
							// 上传失败
						}
					}
				};
				xhr.open('POST', '/uploadUrl', true);
				xhr.send(formData);
			}
		</script>
	</body>

</html>